package com.innovation.ic.im.end.base.thread.data;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.innovation.ic.b1b.framework.manager.ThreadPoolManager;
import com.innovation.ic.im.end.base.handler.im_erp9.RabbitMqHandler;
import com.innovation.ic.im.end.base.model.erp9_sqlserver.Erp9Structures;
import com.innovation.ic.im.end.base.pojo.ServiceResult;
import com.innovation.ic.im.end.base.pojo.constant.RabbitMqConstants;
import com.innovation.ic.im.end.base.service.erp9_sqlserver.Erp9AdminsService;
import com.innovation.ic.im.end.base.service.erp9_sqlserver.Erp9StructuresService;
import com.innovation.ic.im.end.base.service.im_erp9.AccountService;
import com.innovation.ic.im.end.base.service.im_erp9.GroupService;
import com.innovation.ic.im.end.base.thread.AbstractThread;
import com.innovation.ic.im.end.base.value.config.RabbitMqParamConfig;
import com.rabbitmq.client.*;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;

/**
 * @desc   监听erp新增账号队列
 * @author linuo
 * @time   2022年10月17日10:42:16
 */
public class ListenErpAddAccountQueueThread extends AbstractThread implements Runnable{
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /** erp交换机 */
    private String exchange;

    public ListenErpAddAccountQueueThread(Channel channel, String exchange, Erp9StructuresService erp9StructuresService, GroupService groupService,
                                          Erp9AdminsService erp9AdminsService, AccountService accountService, RabbitMqHandler rabbitMqHandler, RabbitMqParamConfig rabbitMqParamConfig, ThreadPoolManager threadPoolManager) {
        this.channel = channel;
        this.exchange = exchange;
        this.erp9StructuresService = erp9StructuresService;
        this.groupService = groupService;
        this.erp9AdminsService = erp9AdminsService;
        this.accountService = accountService;
        this.rabbitMqHandler = rabbitMqHandler;
        this.rabbitMqParamConfig = rabbitMqParamConfig;
        this.threadPoolManager = threadPoolManager;
    }

    @SneakyThrows
    @Override
    public void run() {
        String routingKey = RabbitMqConstants.ERP_ADD_ACCOUNT_QUEUE;
        String queue = routingKey;
        channel.queueBind(queue, exchange, routingKey);
        channel.exchangeDeclare(exchange, RabbitMqConstants.DIRECT_TYPE, true);
        channel.queueDeclare(queue, true, false, false, null);
        Consumer callback = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
                String bodyString = new String(body);
                logger.info("接收到的队列:[{}]的消息为:[{}]", queue, bodyString);
                try {
                    JSONObject jsonObject = JSON.parseObject(bodyString);
                    if(jsonObject != null && !jsonObject.isEmpty()) {
                        // 获取消息名称
                        String msgName = jsonObject.getString(RabbitMqConstants.MESSAGE_NAME_FIELD);
                        if(!msgName.equals(RabbitMqConstants.ERP_ADD_ACCOUNT_QUEUE)){
                            logger.info("mq消息中的方法为:[{}],与当前监听方法:[{}]不一致,不进行后续处理", msgName, RabbitMqConstants.ERP_ADD_ACCOUNT_QUEUE);
                            return;
                        }

                        // 获取消息体
                        JSONObject json = (JSONObject) jsonObject.get(RabbitMqConstants.MESSAGE_BODY_FIELD);
                        if(json != null && !json.isEmpty()) {
                            // 组织架构id
                            String groupId = json.getString(RabbitMqConstants.STRUCTURE_ID_FIELD);

                            // 根据id查询erp中的组织机构信息
                            String groupName = null;
                            ServiceResult<Erp9Structures> serviceResult = erp9StructuresService.selectErp9StructuresById(groupId);
                            if(serviceResult.getResult() != null){
                                groupName = serviceResult.getResult().getName();
                            }

                            // 处理默认群组数据
                            groupService.handleGroupData(groupId, groupName);

                            // 账号id
                            String adminId = json.getString(RabbitMqConstants.ADMIN_ID_FIELD);

                            // 根据账号id查询所属部门
                            String departmentName = null;
                            if(!Strings.isNullOrEmpty(adminId)){
                                ServiceResult<String> stringServiceResult = erp9AdminsService.getDepartmentNameByAdminId(adminId);
                                if(!Strings.isNullOrEmpty(stringServiceResult.getResult())){
                                    departmentName = stringServiceResult.getResult();
                                }
                            }

                            // 处理新增账号的mq数据
                            ServiceResult<Boolean> serviceResult1 = accountService.handleAddAccountRabbitMqData(json, groupName, departmentName);
                            if(serviceResult1.getResult()){
                                // 推送mq消息给前端更新组织机构数据
                                List<String> groupIdList = new ArrayList<>();
                                groupIdList.add(groupId);
                                SendRabbitMqMsgUpdateTreeNodeThread sendRabbitMqMsgUpdateTreeNodeThread = new SendRabbitMqMsgUpdateTreeNodeThread(groupIdList, rabbitMqHandler, rabbitMqParamConfig, accountService);
                                threadPoolManager.execute(sendRabbitMqMsgUpdateTreeNodeThread);
                            }
                        }
                    }
                    logger.info("erp新增账号队列处理结束");
                } catch (Exception e) {
                    logger.error("监听队列:[{}]时出现问题,原因:", queue, e);
                }
            }
        };
        channel.basicConsume(queue, true, callback);
    }
}